// 默认展示文本
export const useText = (text: any) => {
  return isValue(text) ? text : '--';
};

const isValue = (text: any) => {
  return text !== undefined && text !== null && text !== '';
};

type ReturnType = {
  addKeys: (key: string, fn: () => void) => void;
  destoryAllDialog: () => void;
};

// 在路由变化的时候关闭弹窗
export const useDistoryDialog = (): ReturnType => {
  const dialogDistory: { [key: string]: () => void } = {};

  const addKeys = (key: string, fn: () => void) => {
    dialogDistory[key] = fn;
  };
  const destoryAllDialog = () => {
    Object.keys(dialogDistory).forEach(key => {
      dialogDistory[key]();
    });
  };
  return {
    addKeys,
    destoryAllDialog,
  };
};

/**
 * 将数字转为千分位分割
 * @doc 1234 --> 1,234
 * @param num
 */
function formatNumberWithCommas(num: number | string): string {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

/**
 * 将数字转为中文表示
 * @doc 34671234 --> 3,467.1w
 * @doc 346712344 --> 3.467亿
 * @param num
 */
export const useNumberToCN = (num: number): string | number => {
  const changeNumber = (num: number, subNum: number) => {
    const n = subNum >= 100000000 ? 100000 : 1000;
    const n1 = Math.floor(num / subNum);
    const n2 = num - n1 * subNum;
    const n3 = Math.floor(n2 / n);
    const n4 = formatNumberWithCommas(n1 + '.' + n3);
    const str = subNum >= 100000000 ? '亿' : 'w';
    return n4 + str;
  };
  if (num >= 100000000) {
    return changeNumber(num, 100000000);
  } else if (num >= 10000 && num < 1000000000) {
    return changeNumber(num, 10000);
  } else if (num < 10000 && num >= 1000) {
    return formatNumberWithCommas(num);
  } else {
    return num;
  }
};
